package com.nike.main;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import cn.hellotrue.HelloTrue;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nike.bean.CustomName;
import com.nike.dao.NikeDao;
import com.nike.util.IPFactory;

public class NikeLoginThreadMain extends Thread {
	// 版本
	public static String uncoming = "https://www.nike.com/cn/launch/?s=upcoming";
	public static String loginurl = "https://store.nike.com/cn/zh_cn/?l=shop,login_register";
	public static String addressurl = "https://www.nike.com/cn/zh_cn/p/settings";
	private Map<String, Object> zhanghaomap;
	private String ipAndPort;

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghaomap() {
		return zhanghaomap;
	}

	public void setZhanghaomap(Map<String, Object> zhanghaomap) {
		this.zhanghaomap = zhanghaomap;
	}

	public NikeLoginThreadMain(Map<String, Object> zhanghaomap, String ipAndPort) {
		super();
		this.zhanghaomap = zhanghaomap;
		this.ipAndPort = ipAndPort;
	}

	@Override
	public void run() {
		WebDriver wd = null;
		try {
			// 查询数据库，得到已发货的订单
			String telphone = "";
			NikeDao dao = new NikeDao();
			System.setProperty("webdriver.chrome.driver",
					"c:\\chromedriver.exe");

			ChromeOptions cop = new ChromeOptions();
			Proxy proxy = new Proxy();
			proxy.setHttpProxy(ipAndPort).setFtpProxy(ipAndPort)
					.setSslProxy(ipAndPort);
			cop.setProxy(proxy);
			wd = new ChromeDriver(cop);
//			wd = new ChromeDriver();
			String email = zhanghaomap.get("email") + "";
			String pwd = zhanghaomap.get("pwd") + "";
			String lastname = zhanghaomap.get("lastname") + "";
			String firstname = zhanghaomap.get("firstname") + "";
			telphone = zhanghaomap.get("tel") + "";
			System.out.println("电话号码为："+telphone);
			wd.get(loginurl);
			wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			wd.switchTo().defaultContent();
			WebDriverWait wait = new WebDriverWait(wd, 10);
			wait.until(new ExpectedCondition<WebElement>() {
				@Override
				public WebElement apply(WebDriver d) {
					return d.findElement(By.id("nike-unite-loginForm"));
				}
			});
			if (wd.getPageSource().contains("登录NIKE⁠+账号")) {
				WebElement loginForm = wd.findElement(By
						.id("nike-unite-loginForm"));
				WebElement emailAddress = loginForm.findElement(By
						.name("emailAddress"));
				emailAddress.sendKeys(email);
				Thread.sleep(500);
				WebElement password = loginForm
						.findElement(By.name("password"));
				password.sendKeys("Q" + pwd);
				Thread.sleep(500);

				List<WebElement> inputlist = loginForm.findElements(By
						.tagName("input"));
				if (inputlist != null && inputlist.size() > 0) {
					for (WebElement element : inputlist) {
						String text = element.getAttribute("value");
						if (text != null && !"".equals(text)
								&& text.contains("登录")) {
							Thread.sleep(500);
							element.click();
							break;
						}
					}
				}
				Thread.sleep(500);
				//我的账户
				while(true){
					try{
						wd.switchTo().defaultContent();
						if (wd.getPageSource().contains("立即购买")){
							System.out.println("立即购买");
							break;
						}else if(wd.getPageSource().contains("重试")||wd.getPageSource().contains("错误")){
							System.out.println("重试");
							WebElement error = wd.findElement(By.id("nike-unite-error-view"));
							List<WebElement> inputlist2 = error.findElements(By.tagName("input"));
							if(inputlist2!=null && inputlist2.size()>0){
								for(WebElement element : inputlist2){
									String text = element.getAttribute("value");
									if(text!=null && !"".equals(text) && (text.contains("重试")||text.contains("错误"))){
										Thread.sleep(500);
										element.click();
										break;
									}
								}
							}
						}else if(wd.getPageSource().contains("登录")){
							inputlist = wd.findElements(By
									.tagName("input"));
							if (inputlist != null && inputlist.size() > 0) {
								for (WebElement element : inputlist) {
									String text = element.getAttribute("value");
									if (text != null && !"".equals(text)
											&& text.contains("登录")) {
										Thread.sleep(500);
										element.click();
										break;
									}
								}
							}
						}
					}catch(Exception e){
						continue;
					}
				}
				if (wd.getPageSource().contains("立即购买")) {
					String address = "汊河镇" + CustomName.getRoad() + "路"
							+ CustomName.getNum() + "号" + CustomName.getNum() + "室";
					wd.get(addressurl);
					//点击地址
					//等待地址刷新出来
					wait.until(new ExpectedCondition<WebElement>() {
						@Override
						public WebElement apply(WebDriver d) {
							return d.findElement(By.className("edf-title-font-size--xsmall"));
						}
					}).isEnabled();
					Thread.sleep(2000);
					wait.until(new ExpectedCondition<WebElement>() {
						@Override
						public WebElement apply(WebDriver d) {
							return d.findElement(By.className("mobile-number--section"));
						}
					}).isEnabled();
					Thread.sleep(2000);
					//增加手机验证
//					WebElement mobile = wd.findElement(By.className("mobile-number--section"));
//					List<WebElement> mobilebuttonlist = mobile.findElements(By.tagName("button"));
//					if (mobilebuttonlist != null && mobilebuttonlist.size() > 0) {
//						for (WebElement element : mobilebuttonlist) {
//							String text = element.getText();
//							if (text != null && !"".equals(text)
//									&& text.contains("添加")) {
//								Thread.sleep(500);
//								try{
//									element.click();
//								}catch(Exception e){
//									Thread.sleep(2000);
//									element.click();
//								}
//								break;
//							}
//						}
//					}
					//点击添加
					if(telphone==null || "".equals(telphone)||"null".equals(telphone)){
						//如果没有添加手机号码，那么再点击按钮
						
						while(!wd.getPageSource().contains("添加手机号码")){
							WebElement mobile = wd.findElement(By.className("mobile-number--buttons-container"));
							Thread.sleep(500);
							WebElement button = mobile.findElement(By.tagName("button"));
							button.click();
							Thread.sleep(2000);
							wd.switchTo().defaultContent();
						}
						wait.until(new ExpectedCondition<WebElement>() {
							@Override
							public WebElement apply(WebDriver d) {
								return d.findElement(By.className("mobile-number-verify--form"));
							}
						}).isEnabled();
						//获取手机号
						HelloTrue ht = new HelloTrue();
						 String httoken = HelloTrue.TOKEN;
						telphone = ht.getPhone_nike(httoken);
							System.out.println(telphone);
						WebElement mobileNumber = wd.findElement(By.name("mobileNumber"));
						mobileNumber.sendKeys(telphone);
						Thread.sleep(500);
						WebElement verify = wd.findElement(By.className("mobile-number-verify--buttons-container"));
						Thread.sleep(500);
						List<WebElement> querenbuttonlist = verify.findElements(By.tagName("button"));
						if (querenbuttonlist != null && querenbuttonlist.size() > 0) {
							for (WebElement element : querenbuttonlist) {
								String text = element.getText();
								if (text != null && !"".equals(text)
										&& text.contains("确认")) {
									Thread.sleep(500);
									try{
										element.click();
									}catch(Exception e){
										Thread.sleep(2000);
										element.click();
									}
									break;
								}
							}
						}
						Thread.sleep(2000);
						//一直等到编辑手机号码几个字
						while(!wd.getPageSource().contains("编辑手机号码")){
							Thread.sleep(2000);
							wd.switchTo().defaultContent();
						}
						verify = wd.findElement(By.className("mobile-number-verify--buttons-container"));
						querenbuttonlist = verify.findElements(By.tagName("button"));
						if (querenbuttonlist != null && querenbuttonlist.size() > 0) {
							for (WebElement element : querenbuttonlist) {
								String text = element.getText();
								if (text != null && !"".equals(text)
										&& text.contains("获取验证码")) {
									Thread.sleep(500);
									try{
										element.click();
									}catch(Exception e){
										Thread.sleep(2000);
										element.click();
									}
									break;
								}
							}
						}
						//等待verificationCode
						wait.until(new ExpectedCondition<WebElement>() {
							@Override
							public WebElement apply(WebDriver d) {
								return d.findElement(By.name("verificationCode"));
							}
						}).isEnabled();
						//verificationCode
						//输入验证码，点击确认
						WebElement verificationCode = wd.findElement(By.name("verificationCode"));
						String telCode = ht.getMessage_nike(httoken, telphone);
						System.out.println("获取到的验证码信息为：" + telCode);
						if("超时".equals(telCode)){
							try {
								throw new Exception("未获取到验证码");
							} catch (Exception e) {
							}
						}
						String regEx="[^0-9]";   
						Pattern p = Pattern.compile(regEx);   
						telCode = p.matcher(telCode).replaceAll("").trim().substring(0,6);
						System.out.println("截取后的验证码信息为：" + telCode);
						verificationCode.sendKeys(telCode);//输入验证码
						Thread.sleep(500);
						verify = wd.findElement(By.className("mobile-number-verify--buttons-container"));
						querenbuttonlist = verify.findElements(By.tagName("button"));
						if (querenbuttonlist != null && querenbuttonlist.size() > 0) {
							for (WebElement element : querenbuttonlist) {
								String text = element.getText();
								if (text != null && !"".equals(text)
										&& text.contains("确认")) {
									Thread.sleep(500);
									try{
										element.click();
									}catch(Exception e){
										Thread.sleep(2000);
										element.click();
									}
									break;
								}
							}
						}
						wd.switchTo().defaultContent();
						if(wd.getPageSource().contains("已添加")){
							zhanghaomap.put("tel",telphone);
							dao.updateTelphone(zhanghaomap);
						}
						//更新数据库
						//按esc键
						//你的手机号码已添加
						// 表明已经添加好了
						 
					}
					Thread.sleep(3000);
					 //收货，增加收货地址
					List<WebElement> lilist = wd.findElements(By.tagName("li"));
					if (lilist != null && lilist.size() > 0) {
						for (WebElement element : lilist) {
							String text = element.getAttribute("data-content");
							if (text != null && !"".equals(text)
									&& text.contains(".addresses-content")) {
								Thread.sleep(500);
								for(int i=0;i<5;i++){
									try{
										element.click();
										Thread.sleep(1000);
									}catch(Exception e){
										Thread.sleep(2000);
									}
								}
								break;
							}
						}
					}
					Thread.sleep(1000);
					//点击添加
					
					wait.until(new ExpectedCondition<WebElement>() {
						@Override
						public WebElement apply(WebDriver d) {
							return d.findElement(By.className("address-list"));
						}
					}).isEnabled();
					Thread.sleep(2000);
					List<WebElement> buttonlist = wd.findElements(By.tagName("button"));
					if (buttonlist != null && buttonlist.size() > 0) {
						for (WebElement element : buttonlist) {
							
							String text = element.getAttribute("data-type");
							if (text != null && !"".equals(text)
									&& text.contains("shipping")) {
									Thread.sleep(500);
									element.click();
									break;
							}else if (text != null && !"".equals(text)
									&& text.contains("SHIPPING")) {
									
								//表明已经有地址了，那么直接修改状态
								 zhanghaomap.put("province","CN-34");
								 zhanghaomap.put("city","7970");
								 zhanghaomap.put("area","13663");
								 zhanghaomap.put("address","安徽省滁州市来安县"+address);
								 dao.updateLoginStatus(zhanghaomap);
								return;
							}
						}
					}
					Thread.sleep(1000);
					//address-form
					wd.switchTo().defaultContent();
					 WebElement lastNameAddr = wd.findElement(By.id("address-lastname"));
					 lastNameAddr.sendKeys(lastname);
					 Thread.sleep(500);
					 WebElement firstNameAddr = wd.findElement(By.id("address-firstname"));
					 firstNameAddr.sendKeys(firstname);
					 Thread.sleep(500);
//					 String s11="document.getElementsByName('state')[0].value='CN-34';";//安徽省
//					 String s22="document.getElementsByName('city')[0].value='7970';";//滁州市
//					 String s33="document.getElementsByName('district')[0].value='13663'";//来安县
//					 JavascriptExecutor jse = (JavascriptExecutor)wd;
//					 jse.executeScript(s11);
//					 Thread.sleep(500);
//					 jse.executeScript(s22);
//					 Thread.sleep(500);
//					 jse.executeScript(s33);
//					 Thread.sleep(500);
					 WebElement region_container = wd.findElement(By.className("region-container"));
					 
					 List<WebElement> divlist1 =  region_container.findElements(By.tagName("div"));
					 if (divlist1 != null && divlist1.size() > 0) {
							for (WebElement divelement : divlist1) {
								try{
									String css = divelement.getAttribute("class");
									Thread.sleep(1000);
									if(css.contains("country-state-container")){
										List<WebElement> divlistitem1 = divelement.findElements(By.tagName("div"));
										if (divlistitem1 != null && divlistitem1.size() > 0) {
											for (WebElement elementitem : divlistitem1) {
												String cssitem = elementitem.getAttribute("class");
												if(cssitem.contains("container2")){
													elementitem.findElement(By.tagName("a")).click();
													Thread.sleep(1000);
													//找ul下面的li
													WebElement ul = elementitem.findElement(By.tagName("ul"));
													List<WebElement> lilist1 = ul.findElements(By.tagName("li"));
													if (lilist1 != null && lilist1.size() > 0) {
														for (WebElement lielement : lilist1) {
															try{
																String text = lielement.getText();
																if (text != null && !"".equals(text) && text.contains("安徽")) {
																	Thread.sleep(500);
																	lielement.click();
																	break;
																}
															}catch(Exception e){
																continue;
															}
														}
													}
												}
											}
										}
									}else if(css.contains("city-district-container")){
										List<WebElement> divlistitem1 = divelement.findElements(By.tagName("div"));
										if (divlistitem1 != null && divlistitem1.size() > 0) {
											for (WebElement divelementitem : divlistitem1) {
												String cssitem = divelementitem.getAttribute("class");
												Thread.sleep(1000);
												if(cssitem.contains("container1")){
													divelementitem.findElement(By.tagName("a")).click();
													Thread.sleep(2000);
													WebElement ul = divelementitem.findElement(By.tagName("ul"));
													List<WebElement> lilist2 = ul.findElements(By.tagName("li"));
													if (lilist2 != null && lilist2.size() > 0) {
														for (WebElement lielement : lilist2) {
															try{
																String text = lielement.getText();
																if (text != null && !"".equals(text) && text.contains("滁州")) {
																	Thread.sleep(500);
																	lielement.click();
																	break;
																}
															}catch(Exception e){
																continue;
															}
														}
													}
												}else if(cssitem.contains("container2")){
													divelementitem.findElement(By.tagName("a")).click();
													Thread.sleep(2000);
													WebElement ul = divelementitem.findElement(By.tagName("ul"));
													List<WebElement> lilist3 = ul.findElements(By.tagName("li"));
													if (lilist3 != null && lilist3.size() > 0) {
														for (WebElement lielement : lilist3) {
															try{
																String text = lielement.getText();
																if (text != null && !"".equals(text) && text.contains("来安")) {
																	Thread.sleep(500);
																	lielement.click();
																	break;
																}
															}catch(Exception e){
																continue;
															}
														}
													}
												}
											}
										}
									}
								}catch(Exception e){
									continue;
								}
							}
						}
					
					
					
					 WebElement address1 = wd.findElement(By.id("address-addressone"));
					 address1.sendKeys(address);
					 Thread.sleep(500);
					 System.out.println("填写邮编");
					 WebElement postal_wrapper = wd.findElement(By.className("postal-wrapper"));
					 WebElement postalCode = postal_wrapper.findElement(By.id("postalCode"));
					 postalCode.sendKeys("669660");
					 Thread.sleep(500);
					 System.out.println("填写邮编结束");
//					 HelloTrue ht = new HelloTrue();
//					 String httoken = HelloTrue.TOKEN;
//					 String telphone = ht.getPhone_nike(httoken);
//					 System.out.println(telphone);
					 WebElement phoneNumber = wd.findElement(By.id("address-phonenumber"));
					 phoneNumber.sendKeys(telphone);
					 Thread.sleep(500);
					 List<WebElement> buttonlist2 = wd.findElements(By.tagName("button"));
					 if(buttonlist2!=null && buttonlist2.size()>0){
						 for(WebElement element : buttonlist2){
							 String text = element.getText();
							 if(text!=null && !"".equals(text) && text.contains("保存")){
								 element.click();
								 Thread.sleep(5000);
								 //修改数据库相关字段
//								 zhanghaomap.put("tel",telphone);
								 zhanghaomap.put("province","CN-34");
								 zhanghaomap.put("city","7970");
								 zhanghaomap.put("area","13663");
								 zhanghaomap.put("address","安徽省滁州市来安县"+address);
								 dao.updateLoginStatus(zhanghaomap);
								 break;
							 }
						 }
					 }
					 //确定保存成功
				}
			}
			
			// 等待地址添加成功

			// 购买的时候查找 <a> 文字为购买的点击

			// 找li data-size="44" 的点击

			// 找<a> 内容为保存并继续的进行点击

			// 找<a> 内容为提交订单的进行点击

			// 等20秒 ,或者h3 等待付款，或者 前去付款

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// if (wd != null)
			// wd.close();
		}
	}

	public static void exeCmd(String commandStr) {
		// BufferedReader br = null;
		try {
			Runtime.getRuntime().exec(commandStr);
			// br = new BufferedReader(new
			// InputStreamReader(p.getInputStream()));
			// String line = null;
			// StringBuilder sb = new StringBuilder();
			// while ((line = br.readLine()) != null) {
			// sb.append(line + "\n");
			// }
			// System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// finally
		// {
		// if (br != null)
		// {
		// try {
		// br.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// }
	}

	public static void main(String[] args) throws Exception {
		while (true) {
			// 杀掉所有进程,重新启动
			exeCmd("taskkill /F /im chromedriver.exe");
			Thread.sleep(2000);
			exeCmd("taskkill /F /im chrome.exe");
			Thread.sleep(2000);
			// 重启进程
			NikeDao dao = new NikeDao();
			List<Map<String, Object>> list = dao.getAllZhanghaoLogin();
			JSONObject jObject = IPFactory
					.getKdByUrl(IPFactory.ZM_IP_HTTPS_URL_200);
			JSONArray jArray = jObject.getJSONArray("proxy");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> zhanghaomap = list.get(i);
					JSONObject jj = (JSONObject) jArray.get(i);
					String ipAndPort = jj.getString("ip") + ":"
							+ jj.getString("port");
//					String ipAndPort =  IPFactory.getIpByQuanWang();
					NikeLoginThreadMain xt = new NikeLoginThreadMain(
							zhanghaomap, ipAndPort);
					xt.start();
				}
			}
			Thread.sleep(180000);
		}
	}
}
